package indi.gao.file.web;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import indi.gao.file.oss.UploadFileByNameUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.util.*;

/**
 * @author :gaolei
 * @version :v1.0
 * @projectName :GLUtil
 * @description :
 * @createDate :2022/3/10 6:04 下午
 */
@Slf4j
public class Okhttp {
    public static void main(String[] args) throws UnirestException, InterruptedException, IOException {

//        s_shop-mall-billic-smallflow-*

        String[] servers = new String[]{"s_shop-mall-useric-20*", "s_shop-mall-useric-smallflow-*", "s_shop-mall-combination-20*","s_shop-mall-combination-smallflow-*"};


        while (true) {
            if (DateUtil.hour(new Date(), true) % 23 == 0) {
                // 23点删除一次之前的所有文件
                UploadFileByNameUtil.deleteObject("s_shop-mall-useric-error-log");
            }
            long endTime = System.currentTimeMillis();
            long startTime = endTime - 3 * 60;
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder stringBuilder1 = new StringBuilder();


            for (String server : servers) {
                JSONObject message = getMessage(server, Long.toString(startTime), Long.toString(endTime));
                String string = message.get("hits").toString();
                Integer o = Integer.parseInt(JSONObject.parseObject(string).get("total").toString());

                if (o > 0) {
                    Object hits = JSONObject.parseObject(string).get("hits");
                    File tempFile = File.createTempFile("123451234", "4351234.json");
                    // 将格式化后的字符串写入文件
                    Writer write = new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8");
                    write.write(hits.toString());
                    write.flush();
                    write.close();
                    byte[] bytes = FileUtils.readFileToByteArray(tempFile);
                    String s = UploadFileByNameUtil.formUpload(bytes, "s_shop-mall-useric-error-log" + System.currentTimeMillis() + ".json");
                    tempFile.delete();


                    JSONArray objects = JSONObject.parseArray(hits.toString());
                    for (Object object : objects) {
                        JSONObject jsonObject = JSONObject.parseObject(object.toString());
                        Object source = jsonObject.get("_source");
                        JSONObject jsonObject1 = JSONObject.parseObject(source.toString());
                        Object errMsg = jsonObject1.get("errMsg");
                        stringBuilder1.append(errMsg);
                    }

                    String messages = "";
                    if (o > 0) {
                        messages = server + "   " + "[ERROR]数量：" + o + "\n 详情：http://res.hualala.com/" + s;
                    }
                    stringBuilder.append(messages).append("\n");
                }
                log.info(DateUtil.formatDateTime(new Date()) + "    " + server + "   " + o);
            }
            stringBuilder.append("\n").append(stringBuilder1);
            if (stringBuilder.toString().length() > 10) {
                // 发送报警消息
                Map<String, Object> sendObject = new HashMap<>();
                sendObject.put("msgtype", "text");
                Map<String, String> content = new HashMap<>();
                StringBuilder errorMessage = new StringBuilder();
                // 默认显示前1000个字符
                if (stringBuilder.toString().length() >= 1000) {
                    content.put("content", stringBuilder.substring(0, 1000));
                } else {
                    content.put("content", stringBuilder.toString());
                }
                sendObject.put("text", content);
                String post = HttpUtil.post("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=1ba100a6-3c0d-4a70-a098-7687230e3fe6", JSONObject.toJSONString(sendObject));
                log.info(post);
            }
            Thread.sleep(3 * 60 * 1000);
        }
    }

    public static JSONObject getMessage(String serverName, String startTime, String endTime) throws UnirestException {
        Unirest.setTimeouts(0, 0);
        HttpResponse<String> response = Unirest.post("http://kibana.supplychain.logreport.bj.hualala.com/elasticsearch/_msearch")
                .header("kbn-version", "6.4.2")
                .header("Cookie", "_ga=GA1.2.638322063.1616049776; bad_idbaf5eda0-9c1f-11ea-976c-ab9c4067c7dd=ea3f6e01-8a59-11eb-bce8-8755edb1a427; language_type=zh-cn; bad_ida1ab3c90-b152-11ea-8c12-810e7227392c=dd8ade71-8bb1-11eb-b2ac-49e6eba0b6a3; bad_ide03309d0-b151-11ea-8c12-810e7227392c=8d98e0c1-8bb5-11eb-9337-830d2f04fe8c; experimentation_subject_id=eyJfcmFpbHMiOnsibWVzc2FnZSI6IklqZGlZVFF6WTJKa0xUTXdNVGd0TkdJMU55MWhaVGcwTFdRM1kyVTBaR1F5TVRrNFlTST0iLCJleHAiOm51bGwsInB1ciI6ImNvb2tpZS5leHBlcmltZW50YXRpb25fc3ViamVjdF9pZCJ9fQ%3D%3D--d75a745659073bd87e69603c708f77ec596b0b9c; bad_idda577220-b152-11ea-8c12-810e7227392c=286e7522-f9b0-11eb-ad4c-175eb48d3ba0; UM_distinctid=17e6223b2d387d-0ce6618027f5df-1d326253-13c680-17e6223b2d4926; dynamic_code_session=221e0b06-9fb5-449e-b785-4e4a7611f771; access_token=9e06436c-4eab-4df5-a6e1-4419e5859652")
                .header("Content-Encoding", "gzip")
                .header("Host", "kibana.supplychain.logreport.bj.hualala.com")
                .header("Accept-Encoding", "gzip, deflate")
                .header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
                .header("Connection", "keep-alive")
                .header("content-type", "application/x-ndjson")
                .header("Origin", "http://kibana.supplychain.logreport.bj.hualala.com")
                .header("Referer", "http://kibana.supplychain.logreport.bj.hualala.com/app/kibana")
                .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36")
                .header("Accept", "application/json, text/plain, */*")
                .body("{\"index\":\"" +
                        serverName +
                        "\",\"ignore_unavailable\":true,\"timeout\":30000,\"preference\":1646896741466}\n{\"version\":true,\"size\":500,\"sort\":[{\"@timestamp\":{\"order\":\"desc\",\"unmapped_type\":\"boolean\"}}],\"_source\":{\"excludes\":[]},\"aggs\":{\"2\":{\"date_histogram\":{\"field\":\"@timestamp\",\"interval\":\"30m\",\"time_zone\":\"Asia/Shanghai\",\"min_doc_count\":1}}},\"stored_fields\":[\"*\"],\"script_fields\":{},\"docvalue_fields\":[{\"field\":\"@timestamp\",\"format\":\"date_time\"}],\"query\":{\"bool\":{\"must\":[{\"match_all\":{}},{\"match_phrase\":{\"logLevel\":{\"query\":\"[ERROR]\"}}},{\"range\":{\"@timestamp\":" +
                        "{\"gte\":" +
                        startTime +
                        ",\"lte\":" +
                        endTime +
                        ",\"format\":\"epoch_millis\"}}}],\"filter\":[],\"should\":[]," +
                        "\"must_not\":[{ \"match_phrase\": { \"pv\": { \"query\": \"103424\" } } }, { \"match_phrase\": { \"pv\": { \"query\": \"503001\" } } }]" +
                        "}},\"highlight\":{\"pre_tags\":[\"@kibana-highlighted-field@\"],\"post_tags\":[\"@/kibana-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647}}" + "\n")
                .asString();
        JSONObject jsonObject = JSONObject.parseObject(response.getBody());
        List<JSONObject> responses = JSONObject.parseArray(jsonObject.get("responses").toString(), JSONObject.class);
        JSONObject jsonObject2 = responses.get(0);
        return jsonObject2;
    }


}